package main.java.com.async.middleware;

import com.ptc.pfc.pfcSession.Session;
import javafx.concurrent.Service;
import javafx.concurrent.Task;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MutipleTask extends Service<Boolean> {
    private Method _method;
    private Object _object;
    private Session _session;
    private String[] _args;

    public MutipleTask(Object object, String methodName, Session session, String[] args) throws NoSuchMethodException {
        this._object = object;
        this._session = session;
        this._args = args;
        this._method = chooseMethod(_args, _object, methodName);
    }

    @Override
    protected Task<Boolean> createTask() {
        Task<Boolean> task = new Task<Boolean>() {
            @Override
            protected Boolean call() throws Exception {
                if(_args.length == 0){
                    _method.invoke(_object, _session);
                }
                else {
                    _method.invoke(_object, _session, _args);
                }
                return true;
            }
        };
        return task;
    }

    /**
     * 根据参数情况选择有参还是无参的方法来实现
     * @param args 字符串数组参数,按照实际方法的参数顺序填写
     * @param object 调用方法的类对象
     * @param methodName 方法名称
     * @return
     * @throws NoSuchMethodException
     */
    private Method chooseMethod(String[] args, Object object, String methodName) throws NoSuchMethodException {
        if(args.length == 0){
            return object.getClass().getMethod(methodName, Session.class);
        }
        else {
            return object.getClass().getMethod(methodName, Session.class, String[].class);
        }
    }
}
